package pew.pong;

import com.jme3.app.SimpleApplication;
import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.network.serializing.Serializer;
import com.jme3.renderer.RenderManager;
import com.jme3.system.JmeContext;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import pew.pong.network.message.ShutdownServerMessage;

/**
 * test
 * @author normenhansen
 */
public class PongServer extends SimpleApplication implements ConnectionListener, MessageListener<HostedConnection> {
    private Server server;
    
    public static void main(String[] args) {
        Logger.getLogger("PongLog").setLevel(Level.ALL);
        Logger.getLogger("PongLog").addHandler(new ConsoleHandler());
        
	int port = 6143;
	if (args.length > 0) {
	    port = Integer.parseInt(args[0]);
	}
	
        PongServer app = new PongServer(port);
        app.start(JmeContext.Type.Headless);
    }
    private final int port;

    private PongServer(int port) {
	this.port = port;
    }

    @Override
    public void simpleInitApp() {
	Serializer.registerClass(ShutdownServerMessage.class);
        try {
            server = Network.createServer(port);
            server.addConnectionListener(this);
	    server.addMessageListener(this, ShutdownServerMessage.class);
            server.start();
        } catch (IOException ex) {
            Logger.getLogger("PongLog").throwing("PongServer","simpleInitApp", ex);
        }
    }

    @Override
    public void simpleUpdate(float tpf) {
        //TODO: add update code
    }

    @Override
    public void simpleRender(RenderManager rm) {
        //TODO: add render code
    }

    public void connectionAdded(Server server, HostedConnection conn) {
        Logger.getLogger("PongLog").log(Level.INFO, "--- Got connection from " + conn.getAddress() + " Number of connections: " + server.getConnections().size());
    }

    public void connectionRemoved(Server server, HostedConnection conn) {
        Logger.getLogger("PongLog").log(Level.INFO, "--- Lost connection from " + conn.getAddress() + " Number of connections: " + server.getConnections().size());
    }
    
    @Override
    public void destroy() {
	server.close();
	super.destroy();
    }

    public void messageReceived(HostedConnection source, Message m) {
	if (m instanceof ShutdownServerMessage) {
	    Logger.getLogger("PongLog").info("--- Server shutting down " + Thread.currentThread());
	    for (HostedConnection hc : server.getConnections()) {
		hc.close("Server shutting down.");
	    }
	    stop();
	}
    }
}
